<style scope lang="less">
.tab-knowledge {
    width: calc(100% - 20px);
    height: calc(100% - 20px);
    min-width: 1024px;
    margin-top: 10px;
    background-color: white;

    .toolbar {
        display: flex;
        padding-top: 20px;
        padding-bottom: 10px;

        .class-btn {
            padding: 3px 20px 3px 20px;
            background-image: url(../../../assets/images/class-btn-unselect.png);
            background-repeat: no-repeat;
            background-size: 15px 80%;
            background-position: center right;
            cursor: pointer;
        }

        .class-btn-active {
            background-image: url(../../../assets/images/class-btn-select.png);
            background-repeat: no-repeat;
            background-size: 100% 100%;
            margin: 0px 0px 0px 20px;
            color: #fff;
        }

        .more {
            padding: 3px 20px 3px 15px;
            margin-left: auto;
            cursor: pointer;
            color: #b3b3b3;
        }
    }

    .exam-table {
        padding: 0 30px;
        overflow-y: auto;

        .card {
            width: 200px;

            .image {
                width: 100%;
                height: 150px;
            }

            .comment {
                text-align: center;
                padding: 10px;
            }
        }
    }

    .table-footer {
        text-align: right;
        justify-content: flex-end !important;
        background: #ffffff;
        padding-bottom: 20px;
        padding-top: 10px;
        width: calc(100% - 50px);
    }

    .exam-table3 {
        width: 100%;
        height: 100%;
        position: fixed;
        background: rgba(0, 0, 0, 0.3);
        z-index: 101;
        left: 0;
        top: 0;
    }

    .exam-table2 {
        width: 100%;
        height: 100%;
        position: fixed;
        background: rgba(0, 0, 0, 0.3);
        z-index: 99;
        left: 0;
        top: 0;
    }

    .exam-table3 > .center {
        padding-bottom: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
        overflow: hidden;
        min-width: 800px;
        left: 50%;
        top: 50%;
        position: absolute;
        transform: translate(-50%, -50%);
        background: #fff;
        max-height: 80%;
    }

    .exam-table2 > .center {
        padding-bottom: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
        overflow: hidden;
        min-width: 800px;
        left: 50%;
        top: 50%;
        position: absolute;
        transform: translate(-50%, -50%);
        background: #fff;
        max-height: 80%;
    }

    .center_title {
        padding: 10px 0;
        width: 100%;
        height: 40px;
        line-height: 40px;
        text-align: center;
        position: relative;
        background: #ffffff;
    }

    .center_title button {
        position: absolute;
        font-size: 20px;
        color: #888;
        right: 20px;
        top: 50%;
        transform: translateY(-50%);
    }

    .border-bottom {
        border-bottom: 1px solid #e6e6e6;
    }

    .collapse {
        width: 80%;
    }

    em {
        font-style: normal;
        color: #0919f5;
    }

    .exam-table3-box {
        min-width: 800px;
        left: 50%;
        top: 50%;
        position: absolute;
        transform: translate(-50%, -50%);

        .table-footer {
            width: 100%;
        }
    }
}
</style>

<template>
    <div class="tab-knowledge">
        <div class="toolbar">
            <div :class="{'class-btn-active': currentKnowledgeClass === item.name || (index === 0 && !currentKnowledgeClass), 'class-btn': true}"
                 :key="item.name"
                 @click="selectKnowledgeClass(item.name)"
                 v-for="(item, index) in knowledgeType">{{item.name}}
            </div>
        </div>
        <div class="exam-table"
             v-if="currentKnowledgeClass == '未完成考试'">
            <table-ex :columns="columns"
                      :on-operation="onClickOperation"
                      :on-option="onClickOption"
                      :on-page-change="onPageChange"
                      :rows="examStoreList"
                      :total="examList.total"
                      selection="none" />
        </div>
        <!-- v-else="currentKnowledgeClass === '已完成考试'" -->
        <div class="exam-table"
             v-else>
            <table-ex :columns="finishColumns"
                      :on-operation="onClickOperation"
                      :on-option="onClickOption"
                      :on-page-change="onPageChange"
                      :rows="examStoreList"
                      :total="examStoreData.total"
                      selection="none" />
        </div>

        <!-- 考试详情 -->
        <div @touchmove.prevent
             class="exam-table2"
             v-if="show">
            <!-- businessRecords -->
            <div class="center">
                <div class="center_title">
                    [{{currentBusiness.name}}]
                    <em>考试详情信息</em>
                    <el-button @click="show=false"
                               circle
                               icon="el-icon-close"
                               plain
                               type="text" />
                </div>
                <div style="overflow-y:auto;">
                    <table-ex :columns="detailsColumns"
                              :formatter="onExamDetailFormatter"
                              :on-operation="onClickOperation"
                              :on-option="onClickOption"
                              :on-page-change="onPageChange"
                              :rows="examDetails"
                              :total="examDetailData.total"
                              selection="none" />
                </div>
            </div>
        </div>

        <!-- 打字考试练习 -->
        <div @touchmove.prevent
             class="exam-table2"
             v-if="exam">
            <!-- businessRecords -->
            <div class="center">
                <div class="center_title">
                    [{{examName}}]
                    <em>考试详情信息</em>
                    <el-button @click="exam=false"
                               circle
                               icon="el-icon-close"
                               plain
                               type="text" />
                </div>
                <div style="overflow-y:auto;">
                    <table-ex :columns="numberExamColumns"
                              :formatter="onExamDetailFormatter"
                              :on-operation="onClickOperation"
                              :on-option="onClickOption"
                              :on-page-change="onPageChange"
                              :rows="onceExamData"
                              :total="0"
                              selection="none" />
                </div>
            </div>
        </div>
        <!-- score record -->
        <!-- 考试结果 -->
        <exam-result :results="examScoreDetails"
                     :reviewResults="true"
                     @close="scoreShow = false"
                     mode="study"
                     v-if="scoreShow" />
        <!-- 业务列表 -->
        <div @touchmove.prevent
             class="exam-table2"
             v-if="showBusiness">
            <div class="center">
                <div class="center_title">
                    {{currentExam.name}}
                    <em>(考试时间：{{currentExam.startTime}})</em>
                    <el-button @click="showBusiness=false"
                               circle
                               icon="el-icon-close"
                               plain
                               type="text" />
                </div>
                <table-ex :columns="businessColumns"
                          :isFooter="true"
                          :on-option="onClickOption"
                          :on-page-change="onPageChange"
                          :rows="businessList"
                          :total="0"
                          selection="none" />
                <el-button @click="testClick"
                           type="primary">开始考试</el-button>
            </div>
        </div>
    </div>
</template>

<script>
    import { mapActions, mapGetters, mapMutations } from "vuex";
    import { Message } from "element-ui";
    import pageConfig from "./../config";
    import examResult from "@/pages/course/components/examResult";
    import tableEx from "@/components/table/tableEx";
    import api from "@/api";

    export default {
        name: "tab-Exam",

        components: {
            "table-ex": tableEx,
            "exam-result": examResult
        },

        data() {
            return {
                activeNames: ["1"],
                cardList: [],
                knowledgeType: [{ name: "未完成考试" }, { name: "已完成考试" }],
                currentKnowledgeClass: "未完成考试",
                table: "",
                tableFlag: false,
                columns: pageConfig.examColumns,
                finishColumns: pageConfig.finishColumns,
                detailsColumns: pageConfig.examDetail,
                numberExamColumns: pageConfig.numberExamColumns,
                datanull: [],
                currentExam: {},
                currentExamPaper: {},
                currentBusiness: {},
                examDetails: [],
                examScoreDetails: null,
                businessColumns: pageConfig.businessColumns,
                show: false,
                scoreShow: false,
                businessList: [],
                showBusiness: false,
                exam: false,
                examName: ""
            };
        },

        mounted() {
            this.loadInitData();
            console.log(this.numberExamColumns);
        },

        computed: {
            ...mapGetters([
                "loginUser",
                "examList",
                "examStoreData",
                "examDetailData",
                "onceExamData"
            ]),
            examStoreList() {
                let dataList = [];
                if (this.currentKnowledgeClass === "未完成考试") {
                    if (this.examList && this.examList.content) {
                        const list = this.examList.content;
                        for (const item of list) {
                            item.totalScore = item.examPapers[0].score;
                            dataList.push(item);
                        }
                    } else {
                        dataList = [];
                    }
                } else if (this.examStoreData && this.examStoreData.content) {
                    const list = this.examStoreData.content;
                    for (const item of list) {
                        Object.assign(item, item.task);
                        item.totalScore = item.task.examPapers[0].score;
                        dataList.push(item);
                    }
                } else {
                    dataList = [];
                }
                return dataList;
            }
        },

        methods: {
            ...mapActions([
                "getexamlist",
                "getexamstore",
                "getexamdetail",
                "obtainOneExam"
            ]),

            ...mapMutations([
                "setsexamList",
                "SETEXAMPAGE",
                "getExamList",
                "SETEXAMPAGESTORE",
                "SETONCEEXAM"
            ]),

            loadInitData() {
                // 未完成考试
                this.SETEXAMPAGE({
                    loading: false,
                    number: 1,
                    pages: 0,
                    filter: {
                        employeeId: this.loginUser.userInfo.employeeId,
                        examCompleted: false,
                        enabled: true
                    }
                });
                this.getexamlist();

                // 已完成考试
                this.SETEXAMPAGE({
                    loading: false,
                    number: 1,
                    pages: 0,
                    filter: {
                        taskEnabled: true,
                        employeeId: this.loginUser.userInfo.employeeId,
                        examCompleted: true
                    }
                });
                this.getexamstore();
            },

            // 切换考试类型
            selectKnowledgeClass(name) {
                this.currentKnowledgeClass = name;
                this.loadInitData();
            },

            // 开始考试
            testClick() {
                this.$router.push({
                    name: "courseBusiness",
                    query: {
                        course: Base64.encode(
                            JSON.stringify({
                                businessId: this.businessList[0].id,
                                examId: this.currentExam.id,
                                examPaperId: this.currentExamPaper.id,
                                mode: "exam"
                            })
                        )
                    }
                });
                this.$store.commit("course/update", {
                    businessTemplates: this.businessList
                });
            },

            onClickOption() {},

            onClickOperation(oper, row) {
                let examid = row.id;
                let userid = this.$store.state.login.data.loginUser.userInfo
                    .employeeId;
                let data = {
                    examId: examid,
                    employeeId: userid
                };
                console.log("exam", row);
                switch (oper.prop) {
                    case "score": {
                        if (row.lastRecord && row.lastRecord.examStepsContent) {
                            let examStepsContent = JSON.parse(
                                row.lastRecord.examStepsContent
                            );
                            examStepsContent["name"] = row.name;
                            this.examScoreDetails = examStepsContent;
                        }
                        this.scoreShow = true;
                        break;
                    }
                    case "detail": {
                        if (row.businessRecords && row.businessRecords.length) {
                            this.examDetails = row.businessRecords.map(item => {
                                Object.assign(item, item.business);
                                item["score"] = item.lastRecord
                                    ? item.lastRecord.score
                                    : "N/A";
                                item["grade"] = item.lastRecord
                                    ? item.lastRecord.grade
                                    : "N/A";
                                return item;
                            });
                            this.currentBusiness = row;
                            this.show = true;
                        } else if (
                            row.examPapers[0] &&
                            row.examPapers[0].practiceType
                        ) {
                            this.examName = row.task.name;
                            let examid = row.id;
                            let userid = this.$store.state.login.data.loginUser
                                .userInfo.employeeId;
                            let data = {
                                examId: examid,
                                employeeId: userid
                            };

                            this.obtainOneExam(
                                { ...data },
                                {
                                    success: res => {}
                                }
                            );
                            this.exam = true;
                        } else {
                            this.showMessageboxConfig("暂无考试信息!");
                        }
                        break;
                    }
                    case "join": {
                        let self = this;
                        let startStamp = new Date(row.startTime).getTime();
                        let nowStamp = new Date().getTime();
                        let examTime = row.examMinutes * 60 * 1000;
                        if (nowStamp - startStamp >= examTime) {
                            this.showMessageboxConfig("考试已经过期!");
                        } else if (startStamp - nowStamp > 5 * 60 * 1000) {
                            this.showMessageboxConfig("考试尚未开始!");
                        } else {
                            // 进入试卷
                            this.currentExam = row;
                            api.queryOneExam(row.id, {
                                success: exam => {
                                    console.log("exam:", exam);
                                    self.$store.commit("setCurrentExamInfo", exam);
                                    if (exam.examPapers && exam.examPapers.length) {
                                        api.queryOnePaper(exam.examPapers[0].id, {
                                            success: paper => {
                                                this.currentExamPaper = paper;
                                                this.businessList = paper.businessTemplates
                                                    ? paper.businessTemplates
                                                    : null;
                                                if (
                                                    row.examPapers[0] &&
                                                    row.examPapers[0]
                                                        .practiceSpecificType
                                                ) {
                                                    this.$router.push({
                                                        name: "typingTraining",
                                                        query: {
                                                            tabName: this
                                                                .currentExamPaper
                                                                .practiceType,
                                                            operationType: this
                                                                .currentExamPaper
                                                                .practiceSpecificType,
                                                            course: Base64.encode(
                                                                JSON.stringify({
                                                                    examId: this
                                                                        .currentExam
                                                                        .id,
                                                                    examPaperId: this
                                                                        .currentExamPaper
                                                                        .id,
                                                                    mode: "exam"
                                                                })
                                                            )
                                                        }
                                                    });
                                                } else {
                                                    this.showBusiness = true;
                                                }
                                            }
                                        });
                                    } else {
                                        this.showMessageboxConfig(
                                            "未查询到试卷信息!"
                                        );
                                    }
                                }
                            });
                        }
                        break;
                    }
                }
            },

            onPageChange() {},

            showMessageboxConfig(text) {
                Message({
                    center: true,
                    message: text
                });
            },

            onExamDetailFormatter(prop, value, row) {
                if (prop === "timeCost" && value > 0) {
                    value =
                        Math.floor(Number(value) / 60) +
                        "'" +
                        (Number(value) % 60) +
                        "''";
                }
                return value;
            }
        }
    };
</script>
